package com.xuetang.service.impl;

import com.xuetang.entity.CommunityComment;
import com.xuetang.entity.CommunityLike;
import com.xuetang.entity.CommunityPost;
import com.xuetang.mapper.CommunityCommentMapper;
import com.xuetang.mapper.CommunityLikeMapper;
import com.xuetang.mapper.CommunityPostMapper;
import com.xuetang.service.CommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 社区服务实现类
 */
@Service
public class CommunityServiceImpl implements CommunityService {

    @Autowired
    private CommunityPostMapper postMapper;

    @Autowired
    private CommunityCommentMapper commentMapper;

    @Autowired
    private CommunityLikeMapper likeMapper;

    // 社区标签列表
    private static final List<Map<String, Object>> TAGS = Arrays.asList(
            createTag(0, "全部", "#8cc9a1"),
            createTag(1, "求助", "#f0ad4e"),
            createTag(2, "分享", "#5bc0de"),
            createTag(3, "讨论", "#d9534f"),
            createTag(4, "经验", "#9370db"),
            createTag(5, "饮食", "#28a745"),
            createTag(6, "运动", "#fd7e14"),
            createTag(7, "科普", "#17a2b8"));

    private static Map<String, Object> createTag(int id, String name, String color) {
        Map<String, Object> tag = new HashMap<>();
        tag.put("id", id);
        tag.put("name", name);
        tag.put("color", color);
        return tag;
    }

    // 用于生成匿名用户信息
    private static final String[] USER_COLORS = {
            "#8cc9a1", "#5bc0de", "#f0ad4e", "#d9534f", "#9370db", "#20b2aa", "#ff7f50", "#6495ed"
    };

    private static final String[] NICKNAME_PREFIX = {
            "糖友", "健康", "阳光", "快乐", "幸福", "勇敢", "坚强", "智慧",
            "温暖", "善良", "乐观", "平静", "活力", "希望", "自信", "从容"
    };

    @Override
    public Map<String, Object> listPosts(int page, int pageSize, Integer tagId, Long userId) {
        // 计算偏移量
        int offset = (page - 1) * pageSize;

        // 查询帖子列表
        List<CommunityPost> posts = postMapper.listByPage(offset, pageSize, tagId);

        // 统计总数
        int total = postMapper.countPosts(tagId);

        // 获取帖子标签名称
        for (CommunityPost post : posts) {
            setTagName(post);
        }

        // 如果有登录用户，查询点赞状态
        if (userId != null) {
            // 获取所有帖子ID
            List<Long> postIds = posts.stream().map(CommunityPost::getId).collect(Collectors.toList());

            if (!postIds.isEmpty()) {
                // 查询用户点赞状态
                List<CommunityLike> likes = likeMapper.listUserLikes(1, postIds, userId);

                // 转为Map，方便查找
                Map<Long, CommunityLike> likeMap = likes.stream()
                        .collect(Collectors.toMap(CommunityLike::getTargetId, like -> like));

                // 设置帖子点赞状态
                for (CommunityPost post : posts) {
                    post.setLiked(likeMap.containsKey(post.getId()));
                }
            }
        }

        // 组装返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("list", posts);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    @Override
    public CommunityPost getPostDetail(Long id, Long userId) {
        // 查询帖子信息
        CommunityPost post = postMapper.getById(id);

        if (post == null) {
            return null;
        }

        // 设置标签名称
        setTagName(post);

        // 查询评论列表
        List<CommunityComment> comments = commentMapper.listByPostId(id);
        post.setComments(comments);

        // 如果有登录用户，查询点赞状态
        if (userId != null) {
            // 查询帖子点赞状态
            boolean postLiked = likeMapper.checkUserLike(1, id, userId) > 0;
            post.setLiked(postLiked);

            // 如果有评论，查询评论点赞状态
            if (!comments.isEmpty()) {
                // 获取所有评论ID
                List<Long> commentIds = comments.stream().map(CommunityComment::getId).collect(Collectors.toList());

                // 查询评论点赞状态
                List<CommunityLike> commentLikes = likeMapper.listUserLikes(2, commentIds, userId);

                // 转为Map，方便查找
                Map<Long, CommunityLike> likeMap = commentLikes.stream()
                        .collect(Collectors.toMap(CommunityLike::getTargetId, like -> like));

                // 设置评论点赞状态
                for (CommunityComment comment : comments) {
                    comment.setLiked(likeMap.containsKey(comment.getId()));
                }
            }
        }

        return post;
    }

    @Override
    public boolean createPost(CommunityPost post, Long userId) {
        // 设置用户ID
        post.setUserId(userId);

        // 设置默认值
        post.setLikes(0);
        post.setStatus(1);
        post.setCreateTime(LocalDateTime.now());
        post.setUpdateTime(LocalDateTime.now());

        // 图片处理 - 确保images字段是有效的JSON字符串
        if (post.getImages() == null) {
            post.setImages("[]");
        }

        // 生成匿名信息
        if (post.getUserNickname() == null || post.getUserNickname().isEmpty()) {
            generateAnonymousUser(post);
        }

        // 插入数据库
        return postMapper.insert(post) > 0;
    }

    @Override
    public boolean updatePost(CommunityPost post) {
        return postMapper.update(post) > 0;
    }

    @Override
    @Transactional
    public boolean deletePost(Long id) {
        // 先删除评论
        commentMapper.deleteByPostId(id);

        // 再删除帖子
        return postMapper.delete(id) > 0;
    }

    @Override
    public CommunityComment addComment(CommunityComment comment, Long userId) {
        // 设置用户ID
        comment.setUserId(userId);

        // 设置默认值
        comment.setLikes(0);
        comment.setStatus(1);

        // 生成匿名信息
        generateAnonymousUser(comment);

        // 插入数据库
        commentMapper.insert(comment);

        return comment;
    }

    @Override
    public boolean deleteComment(Long id) {
        return commentMapper.delete(id) > 0;
    }

    @Override
    @Transactional
    public boolean likePost(Long postId, Long userId, boolean isLike) {
        // 检查帖子是否存在
        CommunityPost post = postMapper.getById(postId);
        if (post == null) {
            return false;
        }

        // 检查用户是否已点赞
        boolean liked = likeMapper.checkUserLike(1, postId, userId) > 0;

        if (isLike && !liked) {
            // 添加点赞记录
            CommunityLike like = new CommunityLike();
            like.setType(1); // 1-帖子
            like.setTargetId(postId);
            like.setUserId(userId);
            likeMapper.insert(like);

            // 更新帖子点赞数
            postMapper.updateLikes(postId, 1);
            return true;
        } else if (!isLike && liked) {
            // 删除点赞记录
            likeMapper.deleteByTypeAndTargetAndUser(1, postId, userId);

            // 更新帖子点赞数
            postMapper.updateLikes(postId, -1);
            return true;
        }

        return false;
    }

    @Override
    @Transactional
    public boolean likeComment(Long commentId, Long userId, boolean isLike) {
        // 检查评论是否存在
        CommunityComment comment = commentMapper.getById(commentId);
        if (comment == null) {
            return false;
        }

        // 检查用户是否已点赞
        boolean liked = likeMapper.checkUserLike(2, commentId, userId) > 0;

        if (isLike && !liked) {
            // 添加点赞记录
            CommunityLike like = new CommunityLike();
            like.setType(2); // 2-评论
            like.setTargetId(commentId);
            like.setUserId(userId);
            likeMapper.insert(like);

            // 更新评论点赞数
            commentMapper.updateLikes(commentId, 1);
            return true;
        } else if (!isLike && liked) {
            // 删除点赞记录
            likeMapper.deleteByTypeAndTargetAndUser(2, commentId, userId);

            // 更新评论点赞数
            commentMapper.updateLikes(commentId, -1);
            return true;
        }

        return false;
    }

    @Override
    public List<CommunityPost> getRecentPosts(int limit) {
        return postMapper.listRecent(limit);
    }

    @Override
    public List<CommunityComment> getRecentComments(int limit) {
        return commentMapper.listRecent(limit);
    }

    /**
     * 根据ID获取评论
     */
    @Override
    public CommunityComment getCommentById(Long id) {
        return commentMapper.getById(id);
    }

    /**
     * 更新评论
     */
    @Override
    public boolean updateComment(CommunityComment comment) {
        return commentMapper.update(comment) > 0;
    }

    /**
     * 设置帖子标签名称
     */
    private void setTagName(CommunityPost post) {
        for (Map<String, Object> tag : TAGS) {
            if ((Integer) tag.get("id") == post.getTagId()) {
                post.setTagName((String) tag.get("name"));
                break;
            }
        }
    }

    /**
     * 生成匿名用户信息
     */
    private void generateAnonymousUser(CommunityPost post) {
        // 生成随机颜色和昵称
        int colorIndex = new Random().nextInt(USER_COLORS.length);
        int prefixIndex = new Random().nextInt(NICKNAME_PREFIX.length);
        int randomNum = new Random().nextInt(1000);

        post.setUserColor(USER_COLORS[colorIndex]);
        post.setUserNickname(NICKNAME_PREFIX[prefixIndex] + randomNum);
    }

    /**
     * 生成匿名用户信息（评论）
     */
    private void generateAnonymousUser(CommunityComment comment) {
        // 生成随机颜色和昵称
        int colorIndex = new Random().nextInt(USER_COLORS.length);
        int prefixIndex = new Random().nextInt(NICKNAME_PREFIX.length);
        int randomNum = new Random().nextInt(1000);

        comment.setUserColor(USER_COLORS[colorIndex]);
        comment.setUserNickname(NICKNAME_PREFIX[prefixIndex] + randomNum);
    }
}